package com.cmcc.passenger.ui.places

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmcc.passenger.data.AppRequest
import com.cmcc.passenger.data.entity.AddressBook
import com.cmcc.passenger.data.entity.FavoriteAddress
import com.cmcc.shared.Event
import com.cmcc.shared.utils.L
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class PlaceSearchViewModel : ViewModel() {

    private val _selectorCompany = MutableLiveData<Event<Unit>>()
    private val _selectorHome = MutableLiveData<Event<Unit>>()
    private val _selectorFavorite = MutableLiveData<Event<Unit>>()
    val deleteAddress = MutableLiveData<String>()
    val address = MutableLiveData<AddressBook>()

    fun homeSelector(): LiveData<Event<Unit>> {
        return _selectorHome
    }

    fun onHomeClick() {
        _selectorHome.value = Event(Unit)
    }

    fun favoriteSelector(): LiveData<Event<Unit>> {
        return _selectorFavorite
    }

    fun onFavoriteClick() {
        _selectorFavorite.value = Event(Unit)
    }

    fun companySelector(): LiveData<Event<Unit>> {
        return _selectorCompany
    }

    fun onCompanyClick() {
        _selectorCompany.value = Event(Unit)
    }

    private val addAddress = MutableLiveData<String>()

    fun addAddress(address: FavoriteAddress) : MutableLiveData<String>{
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().addAddress(address)
                if (response.isSuccessful) {
                    val data = response.body()
                    addAddress.value = data?.data
                } else {
                    L.d("response error")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return addAddress
    }

    fun getAddress() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().getAddress()
                if (response.isSuccessful) {
                    val data = response.body()
                    address.value = data?.data
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun deleteAddress(id:String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().deleteAddress(id)
                if (response.isSuccessful) {
                    val data = response.body()
                    deleteAddress.value = data?.data
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

}